﻿using KeDa2025_.Utils;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace KeDa2025_
{
    public partial class info : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            IninCity();
            DisplayUserInfo();
            //首先弄一个if首次打开框架
            if (!IsPostBack)
            {
                //当页面打开的时候
                //1)接收传递的id
                //2)根据id查询数据库中的数据
                //3)把查到的数据赋给文本框组件

               
                if (Session != null)
                {

                   // 假设 Session["User"] 存储的是用户信息的 DataRow
                 DataRow userRow = (DataRow)Session["User"];
                    int id = Convert.ToInt32(userRow["id"]); // 从 userRow 中获取 id
                    //int id = Convert.ToInt32(Session["id"]);
                    //int id = Convert.ToInt32(Request.QueryString["id"]);
                    string sql = string.Format("select * from users where id = {0}", id);
                    DataSet ds = DbHelper.Query(sql);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        txtAccount.Text = ds.Tables[0].Rows[0]["account"].ToString();
                        txtBirthday.Text = ds.Tables[0].Rows[0]["birthday"].ToString();
                        txtPwd.Text = ds.Tables[0].Rows[0]["pwd"].ToString();
                        //下拉框
                        ddlCity.SelectedValue = ds.Tables[0].Rows[0]["city_id"].ToString();
                        imgName.ImageUrl = ds.Tables[0].Rows[0]["img_url"].ToString();
                        txtQq.Text = ds.Tables[0].Rows[0]["qq"].ToString();
                        txtEmail.Text = ds.Tables[0].Rows[0]["email"].ToString();
                        txtPhone.Text = ds.Tables[0].Rows[0]["phone"].ToString();
                        //int id = Convert.ToInt32(Request["id"]);
                        //string sql = string.Format("select * from users where id={0}", id);
                        //DataSet ds = DbHelper.Query(sql);
                        //txtAccount.Text = ds.Tables[0].Rows[0]["account"].ToString();
                        //txtBirthday.Text = ds.Tables[0].Rows[0]["birthday"].ToString();
                        //txtPwd.Text = ds.Tables[0].Rows[0]["pwd"].ToString();
                        //ddlCity.Text = ds.Tables[0].Rows[0]["city_id"].ToString();
                        //ratnGender.Text = ds.Tables[0].Rows[0]["gender"].ToString();
                        //imgName.ImageUrl = ds.Tables[0].Rows[0]["img_url"].ToString();
                        //txtPhone.Text = ds.Tables[0].Rows[0]["phone"].ToString();
                        //txtEmail.Text = ds.Tables[0].Rows[0]["email"].ToString();
                        //txtQq.Text = ds.Tables[0].Rows[0]["qq"].ToString();

                    }
                    else
                    {
                        //如果没有数据，提示用户
                        Response.Write("<script>alert('未找到该用户')；</script>");

                    }
                }
                else {
                    Response.Write("<script>alert('请先登录!');window.location.href='Login.aspx'</script>");
                
                }
           

            }
        }

        private void DisplayUserInfo()
        {
            // 假设 `Session["User"]` 存储的是 DataRow，先将其转换为 DataRow
            DataRow userRow = (DataRow)Session["User"];

            // 从 DataRow 中获取用户ID，假设用户ID列名为 "id"
            int userId = Convert.ToInt32(userRow["id"]);

            // 数据库查询以获取用户信息
            string sql = "SELECT account, img_url FROM users WHERE id = @userId";
            using (MySqlConnection conn = new MySqlConnection("server=localhost;user id=zmy2;password=zmy20020525;database=forum;"))
            {
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@userId", userId);

                conn.Open();
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        // 将用户名绑定到 lbName 标签
                        lbName.Text = reader["account"].ToString();

                        // 将头像URL绑定到 Image1 控件
                        Image1.ImageUrl = reader["img_url"].ToString();
                    }
                }
            }
        }

        private void IninCity()
        {
            //string sql = @"SELECT users.*, city.name AS city_name FROM users LEFT JOIN city ON users.city_id = city.id  WHERE users.id = @userId";
            string sql = string.Format("select * from city");
         
            MySqlConnection connection = new MySqlConnection("server=localhost;user id=zmy2;password=zmy20020525;database=forum;");
            MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter(sql, connection);
            DataSet ds = new DataSet();
            // 填充数据集
            sqlDataAdapter.Fill(ds);
            //DataSet ds = DbHelper.Query("select * from province");
            ddlCity.DataSource = ds;
            ddlCity.DataTextField = "name";
            ddlCity.DataValueField = "id";
            ddlCity.DataBind();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //1.捕获文件名称
            string imgname = fileUpImg.FileName;   //a.img
                                                   //2.确定的那个文件保存的物理地址                        
            string path = Server.MapPath("images") + "\\" + imgname;
            //3.进行文件保存
            fileUpImg.SaveAs(path);
            imgName.ImageUrl = "/images/" + imgname;  //"/img/a.jpg"
        }


        protected void btXiugai_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(Request["id"]);
            string account = txtAccount.Text.Trim();
            string birthday = txtBirthday.Text.Trim();
            string pwd = txtPwd.Text.Trim();
            int city = Convert.ToInt32(ddlCity.SelectedValue);
            int gender = Convert.ToInt32(ratnGender.SelectedValue);
            string image = imgName.ImageUrl;
            string phone = txtPhone.Text.Trim();
            string email = txtEmail.Text.Trim();
            string qq = txtQq.Text.Trim();

            //更新语句
            string sql = string.Format("UPDATE users SET birthday = '{0}', pwd = '{1}', city_id = '{2}', gender = '{3}', img_url = '{4}', phone = '{5}', email = '{6}', qq = '{7}' WHERE account = '{8}'",
                            birthday, pwd, city, gender, image, phone, email, qq, account);
            // 建立数据库连接
            string connectionString = "server=localhost;user id=zmy2;password=zmy20020525;database=forum;";
            MySqlConnection connection = new MySqlConnection(connectionString);

            // 创建MySQLCommand对象
            MySqlCommand cmd = new MySqlCommand(sql, connection);

            // 执行SQL语句并获取结果
            connection.Open();
            int flag = cmd.ExecuteNonQuery();
            connection.Close();
            if (flag > 0)
                Response.Write("<script>alert('更新成功');window.location.href='index.aspx'</script>");
            // 刷新页面以显示最新评论

            //Response.Redirect("index.aspx?id=" + id);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script> window.opener.location.reload();window.close();</script>");
        }
    }
}
